package com.kehutong.charge.service.impl;

import java.util.List;
import java.util.Map;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;
import com.kehutong.charge.entity.ChargePayConfig;
import com.kehutong.charge.service.ChargePayConfigService;
import com.kehutong.charge.util.CommonClient;
import com.kehutong.common.DoveClient;
import com.kehutong.common.errcode.Result;

/**
 * @program: kht
 * @description: PayConfigServiceImpl
 * @author: joneron
 * @create: 2021/6/29
 **/
public class ChargePayConfigServiceImpl implements ChargePayConfigService {

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private CommonClient commonClient;
    @Inject
    private DoveClient doveClient;

    @Override
    public Page<ChargePayConfig> findPage(JSONObject jsonObject)  {
        FindPage<ChargePayConfig> find = jdbcSession.findPage(ChargePayConfig.class)
                .eq("deleted", false)
                .order("createTime", "desc");

        find.page(jsonObject);

        Page<ChargePayConfig> page = find.exe();

        try{
            Map<String,JSONObject> communityMap = commonClient.getCommunityMap();
            page.getList().forEach(item->{
                JSONObject community = communityMap.get(item.getCommunityNo());
                if(Objects.nonEmpty(community)){
                    item.setCommunityName(community.getString("name"));
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
        return page;
    }

    @Override
    public List<ChargePayConfig> findList(JSONObject jsonObject) {
        return jdbcSession.findArray(ChargePayConfig.class)
                .eq("deleted", false)
                .eq("status",true)
                .exe();
    }

    @Override
    public Object save(ChargePayConfig chargePayConfig) {
        try {
            // sync admin merchant
            JSONObject jsonObject = doveClient.post("/payment/merchant/service/sync", (http) -> {
                http.setBody(JSONObject.toJSONString(chargePayConfig));
            });
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(0, e.getMessage());
        }
        return jdbcSession.insert(chargePayConfig);
    }

    @Override
    public Object update(ChargePayConfig chargePayConfig) {
        return jdbcSession.updateById(chargePayConfig);
    }

    @Override
    public Object deleteById(String id) {
        ChargePayConfig result = Pool.get(ChargePayConfig.class, id);
        if (result != null) {
            result.setDeleted(true);
            jdbcSession.updateById(result);
        }
        return 1;
    }
}
